class Counter{
    private int count = 0;
    public void add(){
        synchronized (this){//这里的this是一个简化写法,是指向counter的加锁
            //把锁加到线程里面,和加入这里是没有区别的
            //是对this加锁,所以不同的对象进行调用就是没有进行加锁的
            count++;
        }
    }

    static void fun(){
        synchronized (Counter.class){
            //这里是对类对象进行加锁,所以不管怎样调用都会进行加锁并阻塞
        }
    }

    public int getCount(){
        return count;
    }
}
public class Demo2 {
    public static void main(String[] args) throws InterruptedException {
        Counter counter = new Counter();
        //Object locker = new Object();
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        Thread t2 = new Thread(()->{
            for (int i = 0; i < 50000; i++) {
                counter.add();
            }
        });

        t1.start();
        t2.start();
        t1.join();
        t2.join();

        System.out.println("count = "+counter.getCount());
    }
}
